package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.pojos.AdUser;
import com.heima.user.service.AdUserService;
import com.heima.user.mapper.AdUserMapper;
import com.heima.model.common.dtos.admin.AdminLoginDto;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author Fu319
* @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
* @createDate 2025-04-09 10:28:26
*/
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService{
    @Autowired
    private AdUserMapper adUserMapper;
    /**
     * admin端登录功能实现
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdminLoginDto dto) {
        //检查参数
        if(dto.getName()==null || dto.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //调用mapper获取该用户信息
        AdUser adUser = adUserMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if(adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String salt = adUser.getSalt();
        String password = dto.getPassword();
        String saltPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if(saltPassword.equals(adUser.getPassword())){
            //更新登录时间
            adUser.setLoginTime(new Date());
            adUserMapper.updateById(adUser);
            Map<String,Object> map  = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(Long.valueOf(adUser.getId())));
            adUser.setSalt("");
            adUser.setPassword("");
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}




